import time

start_time = time.time()
import os
import numpy as np
import pandas as pd
from keras.models import load_model
import pickle
import warnings
warnings.filterwarnings("ignore", message="X does not have valid feature names")
# 配置路径
testfile_path = r"F:\dataset\BQW_min\Group\A2\202506.csv"
# testfile_path = r'E:\venv2\up_time_predict\4211.csv'
model_path = r"F:\time_series_my_algorithm\60min\权重文件\GeneratorTemperature6\2\grGeneratorTemperature6_Model.h5"
scaler_path = r"F:\time_series_my_algorithm\60min\权重文件\GeneratorTemperature6\2\grGeneratorWindingTemperature6_scaler.pkl"
# output_folder = r'F:\dataset\test\out'  # 结果保存目录
# os.makedirs(output_folder, exist_ok=True)

# 加载资源和配置参数
time_name = 'rectime'
target_name = 'V76'  #####
'''feature_data = pd.read_csv(
    r"F:\time_series_my_algorithm\feature\A2_10days\grGearboxOilTemperture\A2_noA1_A4\grGearboxOilTemperture_importance.csv")  #####
need_names = feature_data.iloc[0:4, 0].tolist()  ##########
'''

# need_names = ['V72', 'V78', 'V37', 'V76']

need_names = ['V37', 'V77']
N_past_value = 60  # 与训练时一致
Pre_size = 60  # 预测步长
Lstm_input_size = len(need_names) + 1  # 特征数量

# 加载测试数据
df_test = pd.read_csv(testfile_path)
print(f"测试数据尺寸：{df_test.shape}")


# 数据预处理函数
def prepare_data(data, scaler):
    # 提取目标列和特征列
    target = data[[target_name]].values
    features = data[need_names].values
    # 合并并缩放
    full_data = np.concatenate([target, features], axis=1)
    scaled_data = scaler.transform(full_data)
    return scaled_data[:, 0], scaled_data[:, 1:], target  # 返回(y, X,原始y)


# 加载scaler
with open(scaler_path, 'rb') as f:
    scaler = pickle.load(f)

# 加载模型
model = load_model(model_path)
# print(model.summary())
# 随机选择预测起点
max_start = len(df_test) - N_past_value - Pre_size
start_idx = np.random.randint(0, max_start)
print(f"\n随机选择起始索引：{start_idx}")

# 准备输入数据
raw_segment = df_test.iloc[start_idx:start_idx + N_past_value + Pre_size]
y_scaled, X_scaled, y_true = prepare_data(raw_segment, scaler)

# 构建输入序列 (符合模型预期的三维结构)
sequence = np.concatenate([
    y_scaled[:N_past_value].reshape(-1, 1),
    X_scaled[:N_past_value]
], axis=1)[np.newaxis, ...]  # 添加batch维度

# 进行预测
#pred_scaled = model.predict(sequence)[0, :, 0]  # 获取预测序列
pred_scaled = model.predict(sequence)[0, :]
# 逆标准化预测结果
pred_full = np.concatenate([
    pred_scaled.reshape(-1, 1),
    X_scaled[N_past_value:N_past_value + Pre_size]
], axis=1)
pred = scaler.inverse_transform(pred_full)[:, 0]

# 获取真实值
true_values = y_true[N_past_value:N_past_value + Pre_size].flatten()
end_time = time.time()
print(f"代码运行时间：{end_time - start_time:.2f}秒")
print(true_values - pred)
# print('true', true_values)
# print('pre', pred)
'''# 逆标准化修正部分
pred_target_scaled = pred_scaled.reshape(-1, 1)
true_values_scaled = y_scaled[N_past_value:N_past_value + Pre_size].reshape(-1, 1)

# 创建临时数组进行目标列逆变换
temp_pred = np.zeros((Pre_size, Lstm_input_size))
temp_pred[:, 0] = pred_target_scaled.flatten()

temp_true = np.zeros((Pre_size, Lstm_input_size))
temp_true[:, 0] = true_values_scaled.flatten()

pred = scaler.inverse_transform(temp_pred)[:, 0]
true_values_original = scaler.inverse_transform(temp_true)[:, 0]

# 时间索引优化
start_time = raw_segment.iloc[N_past_value]['rectime']
time_index = pd.date_range(
    start=start_time,
    periods=Pre_size,
    freq=pd.infer_freq(df_test['rectime'])
)'''
# print(true_values)
# print(pred)

# # 保存结果
# results = pd.DataFrame({
#     'Time': raw_segment.iloc[N_past_value:]['rectime'].values,
#     'TrueValue': true_values,
#     'PredictedValue': pred,
#     'ERR': true_values - pred
# })
# results.to_csv(os.path.join(output_folder, 'prediction_results.csv'), index=False)
# # print(true_values - pred)
# # 可视化对比
# plt.figure(figsize=(12, 6))
# plt.plot(results['Time'], results['TrueValue'], label='True Values', marker='o')
# plt.plot(results['Time'], results['PredictedValue'], label='Predicted Values', marker='x', linestyle='--')
# plt.title(f'Temperature Prediction Comparison\n({N_past_value}s input → {Pre_size}s prediction)')
# plt.xlabel('Time')
# plt.ylabel('Temperature')
# plt.xticks(rotation=45)
# plt.legend()
# plt.tight_layout()
# plt.savefig(os.path.join(output_folder, 'prediction_comparison.png'))
# plt.show()
#
# print("预测结果已保存至：", output_folder)
